﻿using Newtonsoft.Json;
using QWManage.Model;
using QWManage.Utils;
using System;

namespace QWManage.API.UserDetail90196
{
    /// <summary>
    /// 读取成员
    /// </summary>
    public class UserDetailAPI
    {
        //请求方式：GET（HTTPS）
        //请求地址：https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&userid=USERID

        public static UserInfo Invoke(string token, string userid)
        {
            string result = "";
            try
            {
                string url = $"https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={token}&userid={userid}";

                result = HttpHelper.GetHtmlSource(url);
                try
                {
                    var root = JsonConvert.DeserializeObject<Root1st.Root>(result);
                    if (root == null || root.errcode != 0)
                        throw new Exception("API读取成员出错：UserID=" + userid);
                    return new UserInfo()
                    {
                        UserID = root.userid,
                        Name = root.name,
                        Alias = root.alias,
                    };
                }
                catch
                {
                    var root = JsonConvert.DeserializeObject<Root2ed.Root>(result);
                    if (root == null || root.errcode != 0)
                        throw new Exception("API读取成员出错：UserID=" + userid);
                    return new UserInfo()
                    {
                        UserID = root.userid,
                        Name = root.name,
                        Alias = root.alias,
                    };
                }
            }
            catch (Exception ex)
            {
                Logs.LogMgr.Log(ex);
                Logs.LogMgr.Log(ex.Message, "Result=" + result);
                throw ex;
            }
        }
    }
}
